package com.hcloud.auth.third;

import com.hcloud.auth.api.token.ThirdAuthenticationToken;
import com.hcloud.auth.service.ThirdUserService;
import com.hcloud.common.sms.exception.WrongSmsCodeException;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * 短信登录验证逻辑
 * 由于短信验证码的验证在过滤器里已完成,这里直接读取用户信息即可
 * @author hepangui
 * @date 2018-12-13
 */
@AllArgsConstructor
public class ThirdAuthenticationProvider implements AuthenticationProvider {

    /**
     * 获取用户信息
     */
    private final ThirdUserService thirdUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ThirdAuthenticationToken authenticationToken = (ThirdAuthenticationToken) authentication;
        UserDetails user = thirdUserService.loadUser((String)authenticationToken.getPrincipal(),authenticationToken.getLoginType());
        if(user==null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        ThirdAuthenticationToken authenticationResult = new ThirdAuthenticationToken(user,user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //判断传进来的东西是不是SmsCodeAuthentication这种类型的
        return ThirdAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
